package com.hl.card.award.service.impl;

import com.hl.card.modular.packBack.service.IMarketingManageService;
import com.hl.card.modular.packBack.service.ISalesDivisionService;
import com.hl.card.award.service.IRewardByTrans;
import com.hl.card.award.service.ISignRewardByTrans;

import com.hl.card.common.persistence.model.MarketingManage;

import com.hl.card.common.util.ResponseObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * java类简单作用描述
 *
 * @ProjectName: distdev
 * @Package: com.hl.card.modular.pack.service.impl
 * @ClassName: ${TYPE_NAME}
 * @Description: java类作用描述
 * @Author: 作者姓名
 * @CreateDate: 2018/7/9 17:41
 * @UpdateUser: Neil.Zhou
 * @UpdateDate: 2018/7/9 17:41
 * @UpdateRemark: The modified content
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
@Service
public class SignRewardByTransImpl implements ISignRewardByTrans {

    private static final Logger logger = LoggerFactory.getLogger(SignRewardByTransImpl.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    ISalesDivisionService iSalesDivisionService;

    @Autowired
    private IRewardByTrans rewardByTrans;

    @Autowired
    private IMarketingManageService marketingManageService;

    @Value("${spring.profiles.active}")
    private String profiles;

    public ResponseObject userSign(String userId) {
        MarketingManage marketingManage = getSignConfig();
        if(marketingManage == null) {
            marketingManage = new MarketingManage();
            marketingManage.setContinuous(0);
            marketingManage.setFirstday(1);
        }
        String prodCode = "MRQD";
        String signKey = rewardByTrans.getAwardKey(userId, prodCode);
        String signStatueKey = rewardByTrans.getAwardStatueKey(userId, prodCode);
        //进行奖励
        ResponseObject res = rewardByTrans.getAwardStatue(userId, prodCode);

        int errorCode = res.getErroCode();
        //测试暂时关闭领取状态监测
        System.out.println("当前配置 = " + profiles);
        if("prod".equals(profiles)) {
            if (errorCode != 0) {
                return res;
            }
        }
        Map map = (Map) res.getData();
        int count = (int) map.get("count") + 1;
        int keepingTimes = count/5;
        int tail = count%5;
        String score = Integer.toString(marketingManage.getFirstday());
        if(marketingManage.getContinuous() == 1) {//连续签到开启
            if(keepingTimes == 1 && tail == 0) {//连续5天签到
                score = Integer.toString(marketingManage.getConFiveDay());
            }else if(keepingTimes == 2 && tail == 0) {//连续10天签到
                score = Integer.toString(marketingManage.getConTenDay());
                //stringRedisTemplate.opsForValue().set(rewardByTrans.getAwardKey(userId, prodCode), "0");//重置连续签到次数
            }else {
                score = Integer.toString(marketingManage.getFirstday());
            }
        }

        //res = rewardByTrans.makeDistProfitSplitOneDayOneTime(userId, prodCode, score);
        //测试用,允许无限签到
        System.out.println("当前配置 = " + profiles);
        if("dev".equals(profiles)) {
            res = rewardByTrans.makeDistProfitSplit(userId, prodCode, score, true);
        }else {
            res = rewardByTrans.makeDistProfitSplitOneDayOneTime(userId, prodCode, score);
        }
        errorCode = res.getErroCode();
        if(errorCode == 0) {//签到成功
            Date nextDay;
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            calendar.add(calendar.DATE,1);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
            nextDay = calendar.getTime();
//			calendar.add(calendar.DATE,1);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
//			thirdDay = calendar.getTime();
//			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

//			String dateString = formatter.format(nextDay);
//			System.out.println("当天签到状态过期时间 = " + dateString);
//			dateString = formatter.format(thirdDay);
//			System.out.println("连续签到过期时间 = " + dateString);

            long start = System.currentTimeMillis();
            long end = nextDay.getTime();
            int index = (int)((end - start) / 1000);
            System.out.println("过期秒数 = " + index);
            if(keepingTimes == 2 && tail != 0) {
                stringRedisTemplate.opsForValue().set(signKey, "1", index + 24*60*60, TimeUnit.SECONDS);//设置连续签到过期时间
            }else {
                stringRedisTemplate.opsForValue().set(signKey, Integer.toString(count), index + 24*60*60, TimeUnit.SECONDS);//设置连续签到过期时间
            }
            stringRedisTemplate.opsForValue().set(signStatueKey, "1", index, TimeUnit.SECONDS);//设置当天签到状态过期时间
            //stringRedisTemplate.expire(signStatueKey, index, TimeUnit.SECONDS);
//用日期的方式存在redis本身时区差异的问题，弃用
//			stringRedisTemplate.expireAt(signKey, thirdDay);//设置连续签到过期时间
//			stringRedisTemplate.expireAt(signStatueKey, nextDay);//设置当天签到状态过期时间
        }
        return res;
    }

    public ResponseObject checkSign(String userId) {
        ResponseObject res;
        MarketingManage marketingManage = getSignConfig();
        if(marketingManage == null) {
            marketingManage = new MarketingManage();
            marketingManage.setContinuous(0);
            marketingManage.setFirstday(1);
        }
        String prodCode = "MRQD";
        //进行奖励
        res = rewardByTrans.getAwardStatue(userId, prodCode);
        int errorCode = res.getErroCode();
        if(errorCode != 0) {
            return res;
        }
        Map map = (Map) res.getData();
        int count = (int) map.get("count") + 1;
        int keepingTimes = count/5;
        int tail = count%5;
        if(marketingManage.getContinuous() == 1) {//连续签到开启
            if(keepingTimes == 1 && tail == 0) {//连续5天签到
                count = marketingManage.getConFiveDay();
            }else if(keepingTimes == 2 && tail == 0) {//连续10天签到
                count = marketingManage.getConTenDay();
            }else {
                count = marketingManage.getFirstday();
            }
        }

        res = rewardByTrans.getAwardStatue(userId, "MRQD");
        map = (Map) res.getData();
        map.put("count", count);
        return res;
    }

    public MarketingManage getSignConfig() {
        return marketingManageService.selectMarketing();
    }
}
